<?php

namespace App\Console;

use App\Models\Details;
use App\Models\Orders;
use App\Models\Users;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        //订单过期任务计划
        $schedule->call(function () {
            $datas = Orders::where('status' , 1)->get(['created_at' , 'id' , 'order_sn']);

            if(!empty($datas->first())){
                foreach ($datas as $value){
                    if ($value->created_at->timestamp + 7000 < time()) {
                        //订单已过期
                        $value->status = 5;

                        $value->status_msg = '定时任务执行: 订单未在规定时间支付,自动过期';

                        $value->save();
                    }
                }
            }

        })->everyMinute();


        //没小时获取一次明细数据 时间到了将邀请奖励打入用户余额中
        $schedule->call(function () {
            $datas = Details::where('status' , 1)->get(['id' ,'user_id', 'money' , 'expect_at']);

            if(!empty($datas->first())){
                foreach ($datas as $value){
                    if ($value->expect_at->timestamp < time()) {
                        $user = Users::where('id' , $value->user_id)->first();

                        if(!empty($user)){
                            $user->money += $value->money;

                            $value->status = 3 ;

                            $user->save();

                            $value->save();
                        }
                    }
                }
            }

        })->hourly();
        // $schedule->command('inspire')->hourly();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}
